<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Socket客户端</title>
    <script type="text/javascript" src="../../../res/js/jquery-3.4.1.min.js"></script>
</head>
<script type="text/javascript">
    var ws;
    function WebSocketTest() {
        if ("WebSocket" in window) {
            //alert("您的浏览器支持 WebSocket!");

            // 打开一个 web socket
            ws = new WebSocket("ws://127.0.0.1:8090/ws");
            ws.onmessage = function (evt) {
                var received_msg = evt.data;
                $("#body").html(received_msg);
                alert("数据已接收...");
                alert(received_msg);
            };


            ws.onopen = function () {
                // Web Socket 已连接上，使用 send() 方法发送数据
                let data = "{sendUser:2,toUser:0,message:'首次连接'}";
                ws.send(data);
                console.info("首次发送数据建立连接");
            };

            ws.onmessage = function (evt) {
                var received_msg = evt.data;
                $("#body").append("<div>"+received_msg+"</div>");
                console.info("接收数据");
                console.info(received_msg);
            };

            ws.onclose = function () {
                // 关闭 websocket
                alert("连接已关闭...");
            };
        } else {
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持 WebSocket!");
        }
    }
    $(function () {
        $("#but").on("click",function () {
            let data = "{sendUser:2,toUser:1,message:'"+$("#name").val()+"'}";
            console.info("发送数据");
            // Web Socket 已连接上，使用 send() 方法发送数据
            ws.send(data);
        })
    })
</script>
<body>
<div id="sse">
    <a href="javascript:WebSocketTest()">运行 WebSocket</a>

    <input type="text" id="name" name="name" />
    <input type="button" id="but" value="发送信息"/>
    <div id="body"></div>

</div>
</body>
</html>